import requests
import time
import json

from flask import current_app
from sqlalchemy import Column, Integer, VARCHAR, Text
from sqlalchemy.dialects.mysql import TINYINT


# 业务代码
from hzb.database import db


# 直播详情
class WxModel(db.Model):
    # 表名
    __tablename__ = "hzb_wx_model"
    # 列名，类型，主键等
    id = Column('id', Integer, primary_key=True, comment='')
    js_api_token = Column('js_api_token', VARCHAR(255), comment="微信的jsapi_ticket token")
    js_api_token_update_time = Column('js_api_token_update_time', Integer, comment='最近一次更新时间')
    js_api_ticket = Column('js_api_ticket', VARCHAR(255), comment="微信的js_api_ticket")
    js_api_ticket_update_time = Column('js_api_ticket_update_time', Integer, comment='最近一次更新时间')

    def is_js_api_token_expired(self):
        if self.js_api_token_update_time is None:
            return False
        _delta_time = int(time.time()) - self.js_api_token_update_time
        if _delta_time < 6900:
            return True
        else:
            return False
        pass

    def is_js_api_ticket_expired(self):
        if self.js_api_ticket_update_time is None:
            return False
        _delta_time = int(time.time()) - self.js_api_ticket_update_time
        if _delta_time < 6900:
            return True
        else:
            return False
        pass

    @staticmethod
    def get_js_api_token():
        _model = None
        try:
            _model = WxModel.query.all()[0]
            if _model is not None:
                if _model.is_js_api_token_expired() is True:
                    return _model.js_api_token, _model
        except:
            if _model is None:
                _model = WxModel()
                db.session.add(_model)
        url = current_app.config['WX_JS_TOKEN_API_URL'] % (current_app.config['WX_APP_ID'],
                                                           current_app.config['WX_APP_SECRET'])
        current_app.logger.debug(url)
        resp = json.loads(requests.get(url).content.decode('utf-8', 'ignore'), strict=False)
        _model.js_api_token = str(resp['access_token'])
        _model.update_time = int(time.time())
        db.session.commit()
        return _model.js_api_token, _model

    @staticmethod
    def get_js_api_ticket():
        # 获得jsapi_ticket
        # 获得jsapi_ticket之后，就可以生成JS-SDK权限验证的签名了
        # 获取access_token
        _token, _model = WxModel.get_js_api_token()
        if _model.is_js_api_ticket_expired() is True:
            return _model.js_api_ticket
        # 获取jsapi_ticket
        current_app.logger.debug(current_app.config['WX_JS_TICKET_API_URL'])
        url = current_app.config['WX_JS_TICKET_API_URL'] % _token
        res = json.loads(requests.get(url).content.decode('utf-8', 'ignore'), strict=False)
        _model.js_api_ticket = str(res['ticket'])
        _model.js_api_ticket_update_time = int(time.time())
        db.session.commit()
        return _model.js_api_ticket
